import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { getResultAction, updateResultsAction } from '@/store/action/search';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const { resultData } = useAppSelector((state) => state.search);
  const { results, page, total_count } = resultData;
  const { search } = useLocation();
  const usp = new URLSearchParams(search);
  const dispatch = useDispatch();
  const q = usp.get('q') as string;
  useEffect(() => {
    if (!q) return Toast.show({ content: '搜索关键词不能为空' });
    dispatch(getResultAction(q));
  }, [dispatch, q]);

  // 组件卸载是清除结果
  useEffect(() => {
    return () => {
      dispatch({ type: 'search/saveResult', payload: {} });
    };
  }, [dispatch]);

  // 无限滚动事件
  const loadMore = async () => {
    await dispatch(updateResultsAction(q, page + 1));
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem itemData={item} key={item.art_id} />
        ))}
      </div>
      {/* 使用数组长度比较总数量判断是否加载 */}
      {!!results.length && (
        <InfiniteScroll loadMore={loadMore} hasMore={results.length < total_count} />
      )}
    </div>
  );
}
